
import logging
import re
from os import path
from logging.handlers import TimedRotatingFileHandler

from directory import *

class LoggerUtil:
    def __init__(self):
        logsDir = Directory.getLogDir()
        # 创建log目录
        if not path.exists(logsDir):
            os.makedirs(logsDir, 666)

        self.handlers = {logging.DEBUG: "debug.log",
                         logging.INFO: "info.log",
                         logging.ERROR: "error.log",
                         logging.NOTSET: "all.log"}

        self.__loggers = {}
        self.__creatHandler(logsDir)
        logging.getLogger('').setLevel(logging.NOTSET)
        # all.log以及控制台输出的Handler
        sh = logging.StreamHandler()
        sh.setLevel(logging.NOTSET)
        sh.setFormatter(self.__getFormatter())
        self.__loggers[logging.NOTSET].addHandler(sh)

    def __creatHandler(self, logsDir):
        logLevels = self.handlers.keys()
        for level in logLevels:
            logPath = path.join(logsDir, self.handlers[level])
            logger = logging.getLogger(str(level))
            logger.addHandler(self.__getDefaultHandler(logPath))
            logger.setLevel(level)
            self.__loggers.update({level: logger})

    def __getFormatter(self):
        # log的输出格式
        log_fmt = '%(asctime)s\t[%(levelname)s]: %(message)s'
        formatter = logging.Formatter(log_fmt)
        return formatter

    def __getDefaultHandler(self, logPath):
        handler = TimedRotatingFileHandler(filename=logPath, when="midnight", interval=1, backupCount=7,
                                           encoding="UTF-8")
        handler.suffix = "%Y-%m-%d"
        handler.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}$")
        handler.setFormatter(self.__getFormatter())
        return handler

    def debug(self, log):
        self.__loggers[logging.DEBUG].debug(log)
        self.__loggers[logging.NOTSET].debug(log)

    def info(self, log):
        self.__loggers[logging.INFO].info(log)
        self.__loggers[logging.NOTSET].info(log)

    def error(self, log, exc=None):
        str = log
        if exc is not None:
            str = "%s:\n%s" % (log, exc)
        self.__loggers[logging.ERROR].error(str)
        self.__loggers[logging.NOTSET].error(str)